//
//  Busi.m
//  CMYH
//
//  Created by Loki on 15-5-25.
//  Copyright (c) 2015年 Loki. All rights reserved.
//

#import "Busi.h"
#import "X.h"
#import "Define.h"


@interface Busi() <NSURLConnectionDelegate, NSURLConnectionDataDelegate, NSXMLParserDelegate>
@property (nonatomic, strong) NSMutableDictionary       *params;        // 参数列表
@property (nonatomic, strong) NSURLConnection           *connection;    // 连接
@property (nonatomic, strong) NSDictionary              *headers;       // http头
@property (nonatomic, strong) NSMutableData             *response;      // 响应数据
@property (nonatomic, strong) NSMutableDictionary       *resault;       // 请求回来的数据
@property (nonatomic, strong) NSXMLParser               *xmlParser;     // XML
@property (nonatomic, strong) NSString                  *value;         // 数据值
@end

@implementation Busi


/**
 * 初始化
 * @result
 */
- (instancetype)init {
    self = [super init];
    if (self) {
        _timeout = 40;
        _response = [[NSMutableData alloc] initWithCapacity:0];
    }
    
    return self;
}


/**
 * 获取请求地址
 * @param        method，请求方法
 * @result
 */
- (NSString *)url {
    VERIFY_STRING(_method, nil);
    
    // 获取服务器地址
    NSString *strServer = [XUser stringForKey:kServerAddress];
    if (strServer == nil || strServer.length == 0) {
        return nil;
    }
    
    // 构造请求地址
    NSString *strUrl = [NSString stringWithFormat:@"http://%@/WebService/AndroidService.asmx", strServer];
    
    return strUrl;
}


/**
 * 获取 SOAP 请求数据
 * @param        method，请求方法
 * @result
 */
- (NSString *)soap {
    // 编辑参数列表
    NSMutableString *strParams = [[NSMutableString alloc] initWithCapacity:0];
    NSArray *arrKeys = _params.allKeys;
    for (NSUInteger i = 0; i < arrKeys.count; i++) {
        NSString *strKey = [arrKeys objectAtIndex:i];
        NSString *strValue = [_params objectForKey:strKey];
        if (strValue != nil && strValue.length > 0) {
            [strParams appendFormat:@"<%@>%@</%@>\n", strKey, strValue, strKey];
        }
    }
    
    
    // 创建 SOAP 字符串
    NSString *strSOAP = [[NSString alloc] initWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                         "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
                            "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                         "<soap:Body>\n"
                         "<%@ xmlns=\"http://tempuri.org/\">\n%@</%@>\n"
                         "</soap:Body>\n"
                         "</soap:Envelope>\n\n", _method, strParams, _method];
    
    return strSOAP;
}


/**
 * 添加请求参数
 * @param        param，请求参数
 * @param        key，参数名
 * @result
 */
- (void)addParam:(NSString *)param forKey:(NSString *)key {
    VERIFY_STRING(param, none);
    VERIFY_STRING(param, none);
    if (_params == nil) {
        _params = [[NSMutableDictionary alloc] initWithCapacity:0];
    }
    [_params setObject:param forKey:key];
}


/**
 * 发起请求
 *  默认:
 *      已接口名method作为requestID
 *      缓存时间 默认 0
 *      默认不强制刷新
 *      默认为 非静默模式 即需要显示进度条
 * @result
 */
- (void)query {
    VERIFY_STRING(_method, none);
    // 处理请求ID
    if (_requestID == nil || _requestID.length == 0) {
        _requestID = _method;
    }
    
    // 处理请求地址
    NSString *strUrl = [self url];
    NSURL *url = [[NSURL alloc] initWithString:strUrl];
    
    // 处理 SOAP
    NSString *strSOAP = [self soap];
    NSData *soap = [strSOAP dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@", strSOAP);
    
    // 编辑请求
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    [req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [req addValue:[NSString stringWithFormat:@"http://tempuri.org/%@", _method] forHTTPHeaderField:@"SOAPAction"];
    [req addValue:[NSString stringWithFormat:@"%lu", (unsigned long) soap.length] forHTTPHeaderField:@"Content-Length"];
    [req setHTTPMethod:@"POST"];
    [req setHTTPBody:soap];
    [req setTimeoutInterval:_timeout];
    
    // 发送请求
    _connection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
}


#pragma mark NSURLConnectionDelegate NSURLConnectionDataDelegate
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    if ([connection isEqual:_connection]) {
        NSLog(@"网络请求发生错误【%@】", [error localizedDescription]);
        if (nil != _delegete && [_delegete respondsToSelector:@selector(requestException:withID:)]) {
            NSException *exp = [NSException exceptionWithName:@"NSException"
                                                       reason:@"服務器繁忙或服務器地址配置有誤，請稍後再試！"//[error localizedDescription]
                                                     userInfo:[error userInfo]];
            [_delegete requestException:exp withID:_requestID];
        }
        else {
            NSLog(@"回调对象异常！");
        }
    }
}


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    if ([connection isEqual:_connection]) {
        // 获取头信息
        NSHTTPURLResponse *res = (NSHTTPURLResponse *) response;
        _headers = res.allHeaderFields;
        
        // 重置数据
        [_response setLength:0];
    }
}


-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // 接收数据
    if ([connection isEqual:_connection]) {
        [_response appendData:data];
    }
}


-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // 接收完成，回调代理
    if ([connection isEqual:_connection]) {
        NSLog(@"%@", [NSString stringWithUTF8String:_response.bytes]);
        // 解析数据
        XML *xml = [[XML alloc] initWithData:_response];
        if (_delegete != nil && [_delegete respondsToSelector:@selector(requestFinished:withHeaders:andID:)]) {
            [_delegete requestFinished:xml.data withHeaders:_headers andID:_requestID];
        }
    }
}


@end
